<template>
  <div class="update-account">
    <el-dialog v-el-drag-dialog="{ drag: true, full: false, resize: false }" title="账户修改" :close-on-click-modal="false"
      :visible="true" @close="closeMd" width="40%" append-to-body>
      <el-form :model="fm.ps" :ref="fm.fname" :label-width="'100px'">
        <el-form-item label="我的银行" prop="myBank" :rules="[{ required: true, message: '请选择我的银行', trigger: 'blur' }]">
          <el-select disabled @change="handleBalance" style="width: 100%" v-model="fm.ps.myBank" placeholder="请选择我的银行">
            <el-option v-for="(item, i) in bankOptions" :key="i" :label="item.bankName"
              :value="item.bankName + '/' + item.cardNo" />
          </el-select>
        </el-form-item>

        <el-form-item label="金额类型" prop="moneyType" :rules="[{ required: true, message: '请选择金额类型', trigger: 'blur' }]">
          <el-select filterable style="width: 100%" v-model="fm.ps.moneyType" placeholder="请选择金额类型">
            <el-option v-for="item in moneyOptions" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item
          label="客户名称"
          prop="cusName"
          :rules="[{ required: true, message: '请选择客户名称', trigger: 'blur' }]">
          <el-select
            filterable clearable
            remote reserve-keyword
            :remote-method="remoteMethod"
            style="width: 100%" 
            v-model="fm.ps.cusName" 
            placeholder="请选择客户名称">
            <el-option 
              v-for="(item,index) in cusOptions" 
              :key="index" 
              :label="item.unitName"
              :value="item.serviceMan"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="客户名称" prop="cusIds" :rules="[{ required: false, message: '请选择客户名称', trigger: 'blur' }]">
          <el-select filterable multiple collapse-tags remote reserve-keyword :remote-method="queryCusPageList"
            style="width: 100%" v-model="fm.ps.cusIds" placeholder="请选择客户名称">
            <el-option v-for="(item, index) in cusOptions" :key="index" :label="item.unitName" :value="item.id"
              @click.native="selCusName(item)">
              <span>{{ item.unitName }}</span>
              <span>{{ item.baseUserId.realName + '（' + item.baseUserId.phone + '）' }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="对方户名" prop="transName" :rules="[{ required: false, message: '请输入对方户名', trigger: 'blur' }]">
          <el-input style="width: 100%;" placeholder="请输入对方户名" v-model="fm.ps.transName">
          </el-input>
        </el-form-item>

        <el-form-item label="对方账号" prop="transNum">
          <el-input disabled style="width: 100%;" placeholder="请输入对方账号" v-model="fm.ps.transNum">
          </el-input>
        </el-form-item>

        <el-form-item label="收支状态" prop="tradeStatus" :rules="[{ required: true, message: '请选择收支状态', trigger: 'blur' }]">
          <el-select disabled v-model="fm.ps.tradeStatus" placeholder="请选择收支状态" style="width: 100%">
            <el-option label="收入" value="0"></el-option>
            <el-option label="支出" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="交易时间" prop="tradeTime" :rules="[{ required: true, message: '请选择交易时间', trigger: 'blur' }]">
          <el-date-picker disabled v-model="fm.ps.tradeTime" type="datetime" placeholder="交易日期" style="width: 100%"
            format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
        </el-form-item>

        <el-form-item label="交易金额" prop="tradeMoney" :rules="[
          { required: true, message: '请选择交易时间', trigger: 'blur' },
          this.$rules.isFloat('交易金额必须大于0')
        ]">
          <el-input disabled maxlength="10" style="width: 100%;" placeholder="请输入交易金额" v-model="fm.ps.tradeMoney">
          </el-input>
        </el-form-item>

        <el-form-item label="余额" prop="balance">
          <el-input disabled maxlength="10" style="width: 100%;" placeholder="请选择我的银行，自动查询余额" v-model="fm.ps.balance">
          </el-input>
        </el-form-item>

        <el-form-item label="摘要" prop="remark">
          <el-input type="textarea" maxlength="500" placeholder="款项说明，字数限定500字" :autosize="{ minRows: 5, maxRows: 4 }"
            style="width: 100%;" v-model="fm.ps.remark">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-circle-plus" type="primary" @click="onSubmit" :disabled="fm.sb.load">
            {{ fm.sb.text }}
          </el-button>

          <el-button icon="el-icon-error" @click="closeMd">
            关闭
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from "@/directive/el-drag-dialog";

import {
  updateBankAccount,
  findBalanceByBankInfo
} from "@/api/services/order.service";

import {
  getMoneyTypeDict,
  getBankListDict,
  queryComboCusPageList
} from "@/api/services/common.service";

export default {
  name: "UpdateAccount",
  directives: { elDragDialog },
  props: { myData: Object },
  data() {
    return {

      fm: {
        fname: "updateAccountFm",
        sb: { load: false, text: "信息修改" },
        ps: {
          // 修改id
          id: '',
          // 我的银行
          myBank: '',
          // 金额类型
          moneyType: '',
          // 客户id
          cusIds: [],
          // 客户名称
          cusObjArr: [],
          // 对方户名
          transName: '',
          // 对方账号 
          transNum: '',
          // 收支状态
          tradeStatus: '',
          // 交易时间 
          tradeTime: '',
          // 交易金额
          tradeMoney: '',
          // 余额
          balance: '',
          // 摘要
          remark: '',
        },
      },

      // 金额类型-选择列表
      moneyOptions: [],
      // 银行-选择列表
      bankOptions: [],
      // 客户-选择列表
      cusOptions: [],

    };
  },
  created() {
    this.init();
  },
  methods: {
    closeMd() {
      this.$emit("myClick", { state: false });
    },
    init() {
      const that = this, ps = that.fm.ps;

      // 获取-金额类型-选择数据
      getMoneyTypeDict().then(res => {
        that.moneyOptions = res.mTypes;
      });

      // 获取-银行-选择数据
      getBankListDict().then(res => {
        that.bankOptions = res.banks;
      });

      // 修改-回填数据
      console.log('修改回填数据：', that.myData);
      let o = that.myData?.obj;
      if (o) {
        // 修改id
        ps.id = o.id;
        // 我的银行
        ps.myBank = o.myBankName;
        // 金额类型
        ps.moneyType = o.moneyTypeId.id;
        // // 客户id
        // ps.cusIds = []; 
        // // 客户名称
        // ps.cusObjArr = []; 
        // 对方户名
        ps.transName = o.transName;
        // 对方账号 
        ps.transNum = o.transNum;
        // 收支状态 tradeOutMoney-支出 tradeInMoney-收入
        ps.tradeStatus = o.tradeInMoney > 0 ? '0' : '1';
        // 交易时间 
        ps.tradeTime = o.tradeTime;
        // 交易金额
        ps.tradeMoney = o.tradeInMoney > 0 ? o.tradeInMoney : o.tradeOutMoney;
        // 余额
        ps.balance = o.balance;
        // 摘要
        ps.remark = o.remark;

        // 设置客户数据
        if (o.cusName) {
          let phoneArr = [];
          o.cusName.split('/@').forEach(it => { phoneArr.push(it.split(',')[1]) });
          console.log(phoneArr.join(','))
          queryComboCusPageList({ phoneArr: phoneArr.join(',') }).then((res) => {

            if (res.code == 1) {
              that.cusOptions = res.data;

              let cusIds = [];
              that.cusOptions.forEach(it => { cusIds.push(it.id); });

              // 赋值
              ps.cusIds = cusIds;
              ps.cusObjArr = that.cusOptions;
            }
          });
        }
      }

    },
    // 获取-客户数据列表
    queryCusPageList(query) {
      let { cusObjArr } = this.fm.ps;

      if (!query) return (this.cusOptions = []);

      queryComboCusPageList({ find: query }).then((res) => {
        if (res.code == 1) {
          this.cusOptions = res.data;

          // 追加已选中的数据
          if (cusObjArr.length > 0) this.cusOptions = cusObjArr.concat(this.cusOptions);
        }
      });
    },
    // 客户名称选择
    selCusName(obj) {
      let that = this, { cusIds, cusObjArr } = that.fm.ps;

      let index = cusObjArr.findIndex(it => it.id == obj.id);
      let is = cusIds.findIndex(it => it == obj.id);
      if (is != -1) {// 存在，表示添加
        if (index == -1) cusObjArr.push(obj);
      } else {// 不存在，表示删除
        if (index != -1) cusObjArr.splice(index, 1);
      }
    },
    handleBalance() {
      let ps = {
        bankName: this.fm.ps.myBank.split('/')[0], // 银行名称
        bankNo: this.fm.ps.myBank.split('/')[1], // 银行卡号
      };
      findBalanceByBankInfo(ps).then((res) => {
        if (res.code === 1) {
          this.fm.ps.balance2 = res.balance;
        } else {
          this.fm.ps.balance2 = 0;
        }
      });
    },

    // 提交-表单
    onSubmit() {
      const that = this, U = that.U, fm = that.fm, ps = U.scopy(fm.ps);

      that.$refs[fm.fname].validate((valid) => {
        if (!valid) { return false; } else {
          ps.tradeMoney = Number(ps.tradeMoney);

          if (ps.cusObjArr) {
            let arr = [];
            ps.cusObjArr.forEach(it => {
              arr.push(it.baseUserId.realName + ',' + it.baseUserId.phone);
            });
            ps.cusName = arr.join('/@');
          }
          delete ps.cusIds;
          delete ps.cusObjArr;

          ps.updId = ps.id;
          delete ps.id;

          console.log('银行记账提交前参数', ps);

          fm.sb.load = true;
          updateBankAccount(ps).then((res) => {
            fm.sb.load = false;

            if (res.code === 1) {
              U.qsuccess(res.msg);

              that.closeMd();
              that.$emit("reloadDg");
            } else {
              U.qerror(res.msg);
            }
          });
        }
      });

    }
  },
};
</script>
